package com.example.star.utils;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

public class MusicUploadUtils {

    private static final int REQUEST_PICK_MUSIC = 1;
    private static final int PERMISSION_REQUEST_CODE = 2;

    private Context context;
    private String selectedMusicPath;

    public MusicUploadUtils(Context context) {
        this.context = context;
    }

    public void startMusicUpload() {
        if (checkPermissions()) {
            showMusicPickerDialog();
        }
    }

    private boolean checkPermissions() {
        List<String> requiredPermissions = new ArrayList<>();

        // 动态适配存储权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_MEDIA_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                requiredPermissions.add(Manifest.permission.READ_MEDIA_AUDIO);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 不需要显式请求存储权限
        } else {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                requiredPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
        }

        if (!requiredPermissions.isEmpty()) {
            ActivityCompat.requestPermissions((Activity) context,
                    requiredPermissions.toArray(new String[0]),
                    PERMISSION_REQUEST_CODE);
            return false;
        }
        return true;
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showMusicPickerDialog();
            } else {
                Toast.makeText(context, "权限被拒绝，无法选择音乐", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showMusicPickerDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("选择音乐来源");
        String[] options = {"从本地选择"};
        builder.setItems(options, (dialog, which) -> {
            if (which == 0) {
                pickMusicFromLocal();
            }
        });
        builder.show();
    }

    private void pickMusicFromLocal() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        ((Activity) context).startActivityForResult(intent, REQUEST_PICK_MUSIC);
    }

    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_PICK_MUSIC && data != null) {
                Uri selectedMusic = data.getData();
                selectedMusicPath = getRealPathFromUri(selectedMusic);
            }
        }
    }

    private String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Audio.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);
            cursor.close();
            return path;
        }
        return null;
    }

    public String getSelectedMusicPath() {
        return selectedMusicPath;
    }
}